<!-- eslint-disable no-unused-vars -->
<template>
  <div>
    <el-button type="primary" @click="open">添加区域</el-button>
    <!-- 表单区域 -->
    <template>
      <el-table
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="序号"
          width="100"
        />
        <el-table-column
          prop="areaName"
          label="区域名称"
          width="180"
        />
        <el-table-column
          prop="spaceNumber"
          label="车位数（个）"
          width="130"
        />
        <el-table-column
          prop="areaProportion"
          label="面积（m²）"
          width="120"
        />
        <el-table-column
          prop="ruleName"
          label="计费规则"
          width="200"
        />
        <el-table-column
          prop="remark"
          label="备注"
          width="130"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template #default="{row}">
            <el-button type="text" size="small" @click="handleClick(row)">编辑</el-button>
            <el-button type="text" size="small" @click="deleteArea(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 分页器 -->
    <div class="page-container">
      <el-pagination
        :page-sizes="[2,5, 10,20]"
        :page-size="areaData.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 弹层 -->
    <el-dialog
      :title="dialogTitle"
      :visible="dangerouslyUse"
      width="40%"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="areaData" :model="areaData" :rules="areaDataRules" label-position="top">
          <el-form-item label="区域名称" prop="areaName">
            <el-input v-model="areaData.areaName" placeholder="请输入区域名称" />
          </el-form-item>
          <el-form-item label="车位数（个）" prop="spaceNumber">
            <el-input v-model="areaData.spaceNumber" placeholder="请输入车位个数" />
          </el-form-item>
          <el-form-item label="面积（m²）" prop="areaProportion">
            <el-input v-model="areaData.areaProportion" placeholder="请输入面积" />
          </el-form-item>
          <el-form-item label="关联计费规则" prop="ruleName">
            <el-select v-model="areaData.ruleName" placeholder="请选择">
              <el-option
                v-for="item in selectAreaRules"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="areaData.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dangerouslyUse=false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addAreaAPI, deleteAreaAPI, editAreaAPI, getAreaListAPI } from '@/api/area'

export default {
  data() {
    return {
      // 控制弹层显示与隐藏
      dangerouslyUse: false,
      tableData: [],
      total: 0,
      isEditing: false, // 是否处于编辑模式
      currentRowId: null, // 当前编辑行的ID
      dialogTitle: '', // 弹层标题
      areaData: {
        page: 1,
        pageSize: 10,
        ruleId: null,
        areaName: '',
        areaProportion: null,
        hoverRuleName: '',
        spaceNumber: null,
        remark: '',
        ruleName: ''
      },
      areaDataRules: {
        areaName: [
          { required: true, message: '请输入正确的区域名称', trigger: 'blur' }
        ],
        areaProportion: [
          { required: true, message: '请输入区域面积', trigger: 'blur' }
        ],
        spaceNumber: [
          { required: true, message: '请输入车位数量', trigger: 'blur' }
        ],
        ruleName: [
          { required: true, message: '请选择计费规则', trigger: 'change' }
        ]
      },
      selectAreaRules: [
        {
          id: 0,
          value: '分段计费'
        },
        {
          id: 1,
          value: '按次收费'
        },
        {
          id: 2,
          value: '按小时收费'
        },
        {
          id: 3,
          value: '按分钟收费'
        }
      ]
    }
  },
  created() {
    this.getAreaList()
  },
  methods: {
    async getAreaList() {
      const { data } = await getAreaListAPI(this.areaData)
      console.log(data)
      this.tableData = data.rows
      this.total = data.total
    },
    handleSizeChange(val) {
      this.areaData.pageSize = val
      console.log(`每页 ${val} 条`)
      this.getAreaList()
    },
    handleCurrentChange(val) {
      this.areaData.page = val
      console.log(`当前页: ${val}`)
      this.getAreaList()
    },
    // 打开弹层
    open() {
      // 清空 areaData 的所有字段
      this.areaData = {
        page: 1,
        pageSize: 10,
        ruleId: null,
        areaName: '',
        areaProportion: null,
        hoverRuleName: '',
        spaceNumber: null,
        remark: '',
        ruleName: ''
      }

      // 重置编辑状态
      this.isEditing = false
      this.currentRowId = null

      // 设置弹层标题为“添加区域”
      this.dialogTitle = '添加区域'

      // 打开弹窗
      this.dangerouslyUse = true
    },
    // 新增功能
    confirmAdd() {
      this.$refs.areaData.validate(async valid => {
        if (valid) {
          const formData = {
            areaName: this.areaData.areaName,
            areaProportion: this.areaData.areaProportion,
            spaceNumber: this.areaData.spaceNumber,
            remark: this.areaData.remark,
            ruleId: this.areaData.ruleName // 注意这里 ruleName 是 id
          }

          try {
            if (this.isEditing) {
              // 编辑模式：调用更新接口
              const res = await editAreaAPI(this.currentRowId, formData)
              console.log(res)
              this.$message.success('修改成功')
            } else {
              // 新增模式：调用新增接口
              const res = await addAreaAPI(formData)
              console.log(res)
              this.$message.success('添加成功')
            }

            // 刷新列表并关闭弹窗
            this.getAreaList()
            this.dangerouslyUse = false

            // 重置表单和状态
            this.resetForm()

            // 重置弹层标题
            this.dialogTitle = ''
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败，请稍后再试')
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      if (this.$refs.areaData) {
        this.$refs.areaData.resetFields() // 清空表单校验状态
      }

      // 手动重置 areaData 的所有字段
      this.areaData = {
        page: 1,
        pageSize: 10,
        ruleId: null,
        areaName: '',
        areaProportion: null,
        hoverRuleName: '',
        spaceNumber: null,
        remark: '',
        ruleName: ''
      }

      // 重置编辑状态
      this.isEditing = false
      this.currentRowId = null
    },
    // 编辑功能
    handleClick(row) {
      console.log(row)
      this.dangerouslyUse = true
      this.areaData.areaName = row.areaName
      this.areaData.areaProportion = row.areaProportion
      this.areaData.spaceNumber = row.spaceNumber
      this.areaData.remark = row.remark
      this.areaData.ruleName = row.ruleId
      // 标记为编辑模式，并记录当前行 ID
      this.isEditing = true
      this.currentRowId = row.id
      // 设置弹层标题为“编辑区域”
      this.dialogTitle = '编辑区域'
    },
    // 删除区域
    deleteArea(row) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteAreaAPI([row.id])
        if (res.code === 10000) {
          this.$message.success('删除成功')
          // 更新列表数据
          this.getAreaList()
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container{
  padding:20px 0px;
  text-align: right;
}
</style>
